﻿using System;
using System.Net;
using System.Net.Mail;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Paltop_DatabaseLayer;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
namespace Paltop_.Controllers
{
    public class UserControler
    {
        private PaltopDatabaseEntities db = new PaltopDatabaseEntities();

        public int LoginCheck(String userName, String password)
        {
            try
            {
                userName = userName.ToLower();
                var query = db.Accounts.Where(p => p.Email == userName).FirstOrDefault();
                if (query != null)
                {
                    String pass = query.Password;
                    String hash = PasswordHassher(password);
                    if (hash == pass)
                    {
                        //username and password correct;
                        return query.AccountID;
                    }
                    else
                    {
                        //password wrong;
                        return -1;
                    }
                }
                else
                {
                    //emailaddres worng;
                    return -2;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        public int RegisterNewAccount(String email, String password, String name)
        {
            try
            {
                email = email.ToLower();
                if (MailVarifier(email) && PasswordVarifier(password) && NameVarifier(name) && CheckMailAvailebility(email) == 1)
                {

                    var hashPassword = PasswordHassher(password);
                    var a = new Account { Email = email, Password = hashPassword, Name = name, RegisterDate = DateTime.UtcNow };
                    db.Accounts.AddObject(a);
                    db.SaveChanges();
                    return a.AccountID;
                }
                else
                {
                    return -1;
                }

            }
            catch (Exception)
            {
                return -10;
            }
        }

        public int CheckMailAvailebility(String mail)
        {
            try
            {

                if (!MailVarifier(mail)) return -10;
                mail = mail.ToLower();
                var query = db.Accounts.Where(p => p.Email == mail).ToList();
                if (query.Count < 1)
                    return 1;
                else
                    return -1;
            }
            catch (Exception)
            {

                return -10;
            }

        }


        public string PasswordHassher(string pass)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
            byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
            return Convert.ToBase64String(inArray);
        }

        public bool MailVarifier(String mail)
        {
            string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                       + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                       + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                       + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                       + @"[a-zA-Z]{2,}))$";
            Regex mailRegex = new Regex(patternStrict);
            return mailRegex.IsMatch(mail);
        }

        public bool PasswordVarifier(String pass)
        {

            return (pass.Length >= 6 && pass.Length < 50);

        }

        public bool NameVarifier(String name)
        {
            return (name.Length >= 2 && name.Length < 15);
        }

        public int ForgetPassword(String email)
        {
            try
            {
                var query = db.Accounts.Where(p => p.Email == email).ToList();
                if (query.Count == 0)
                {
                    //Maid does'nt exist in data base
                    return -1;

                }
                else
                {
                    var user = query.FirstOrDefault();
                    MailMessage forgetMail = new MailMessage();
                    forgetMail.From = new MailAddress("paltop@damdam.ir");
                    forgetMail.To.Add(new MailAddress(user.Email));
                    forgetMail.Subject = "Your Paltop Password";
                    String mailBody = "<p> Not implmented yet !!!</p>";
                    forgetMail.Body = mailBody;
                    forgetMail.IsBodyHtml = true;
                    SmtpClient smtpClient = new SmtpClient();
                    smtpClient.Host = "mail.damdam.ir";
                    smtpClient.Port = 25;
                    NetworkCredential cred = new NetworkCredential("paltop+damdam.ir", "onlygod@");
                    smtpClient.EnableSsl = false;
                    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Timeout = 50000;
                    smtpClient.Credentials = cred;
                    smtpClient.Send(forgetMail);
                    return 0;
                }

            }
            catch (Exception)
            {

                return -10;
            }

        }

        public String ResetPassword(int id, String Password)
        {
            var query = db.Accounts.Where(p => p.AccountID == id).ToList();
            if (query.Count < 1)
            {
                return "ERROR";
            }
            else
            {
                var person = query.FirstOrDefault();
                if (person.Password == Password)
                {
                    return PasswordChanger(person);
                }
                else
                {
                    return "ERROR";
                }
            }
        }

        private String RandomPasswordGenerator()
        {
            Random a = new Random();
            String pass = "";
            for (int i = 0; i < 6; i++)
            {

                pass = pass + (char)a.Next(48, 126);

            }
            return pass;
        }
        private String PasswordChanger(Account P)
        {
            try
            {
                String pass = RandomPasswordGenerator();
                P.Password = PasswordHassher(pass);
                db.SaveChanges();
                return pass;
            }
            catch (Exception)
            {

                throw;
            }

        }
        public Account getAccountData(int id)
        {
            try
            {
                return db.Accounts.Where(p => p.AccountID == id).FirstOrDefault();
            }
            catch (Exception)
            {

                return null;
            }
        }


    }
}